package pos.gengshen.com.gspos.utils;


import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/7/6/006.
 */

public class HttpUtils {

    public static void doGet(String address, Map<String,String> head, Map<String,Object> body, okhttp3.Callback callback){

        System.out.println("=====address====="+address);
        String param = "";
        if(body!=null&&body.size()>0){
            for (Map.Entry<String, Object> entry : body.entrySet()) {
                param=entry.getKey()+"="+entry.getValue()+"&";
            }
            address = address+"?"+param;
            System.out.println("OKhttp GET请求"+address);
        }
        OkHttpClient client=new OkHttpClient();

        System.out.println("OKHttp 请求的url"+address+"的值");
        Request.Builder builder=new Request.Builder().url(address);
        if(head!=null&&head.size()>0){
            for (Map.Entry<String, String> entry : head.entrySet()) {
                builder.addHeader(entry.getKey(),entry.getValue());
            }
        }
        Request request=builder.get().build();
        client.newCall(request).enqueue(callback);
    }


    public static void doPost(String address, Map<String,String> head, Map<String,String> body, okhttp3.Callback callback){

        OkHttpClient client=new OkHttpClient();
        Request.Builder builder=new Request.Builder().url(address);
        if(head!=null&&head.size()>0){
            for (Map.Entry<String, String> entry : head.entrySet()) {
                builder.addHeader(entry.getKey(),entry.getValue());
            }
        }
        FormBody.Builder formBody = new FormBody.Builder();
        if(body!=null&&body.size()>0){
            for (Map.Entry<String, String> entry : body.entrySet()) {
                formBody.add(entry.getKey(),entry.getValue());
            }
        }
        RequestBody requestBody = formBody.build();
        Request request=builder.post(requestBody).build();
        client.newCall(request).enqueue(callback);
    }


}
